﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using System.Net.Mail;
using System.Net;

using Microsoft.Exchange.WebServices.Data;
using Microsoft.Exchange.WebServices.Autodiscover;

using System.Net.Security;
using System.Security.Cryptography.X509Certificates;

namespace Microsoft.Exchange.WebServices.WinFormsTest
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click_1(object sender, EventArgs e)
        {

            try
            {
                // Connect to Exchange Web Services as user1 at contoso.com.
                ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2007_SP1);
                service.Credentials = new WebCredentials(oUid.Text, oPwd.Text, oDomainName.Text);
#if DEBUG
                service.TraceEnabled = true;
#else
                service.TraceEnabled = false;
#endif
                service.AutodiscoverUrl(oAutodiscoverUrl.Text);

                // Create the e-mail message, set its properties, and send it to user2@contoso.com, saving a copy to the Sent Items folder. 
                EmailMessage message = new EmailMessage(service);
                message.Subject = oSubject.Text;
                message.Body = oBody.Text;
                message.ToRecipients.Add(oToRecipients.Text);
                message.SendAndSaveCopy();
            }
            catch (Exception err)
            {
                MessageBox.Show(err.Message);
            }
        }

        private void oTest_Click(object sender, EventArgs e)
        {

            // http://www.mytest.org.ru/page/osnovnye-momenty-raboty-s-exchange-web-services-managed-api

            try
            {
                // Connect to Exchange Web Services as user1 at contoso.com.
                ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2007_SP1);
                service.Credentials = new WebCredentials(oUid.Text, oPwd.Text, oDomainName.Text);
#if DEBUG
                service.TraceEnabled = true;
#else
                service.TraceEnabled = false;
#endif
                
                service.AutodiscoverUrl(oAutodiscoverUrl.Text);
                service.Url = new Uri(@"https://mail01.korablik.local/EWS/Exchange.asmx");

                // In Folder
                Folder folder = Folder.Bind(service, new FolderId(WellKnownFolderName.Inbox, "in@korablik.ru"));

                Folder f2 = ListFoldersInInbox(ref service, ref folder);
                if (f2 == null)
                    return;

                string subject = @"Опрос покупателей";
                string subject2 = @"Отзывы покупателей магазинов Кораблик.";

                ItemView view = new ItemView(f2.TotalCount);
                view.PropertySet = new PropertySet() { RequestedBodyType = BodyType.Text };

                FindItemsResults<Item> findResults;
                do
                {
                    /*
                    findResults = service.FindItems(
                        WellKnownFolderName.Inbox,
                        new SearchFilter.IsEqualTo(EmailMessageSchema.IsRead, true),
                        view);
                    */

                    //findResults = service.FindItems(
                    //      f2.Id
                    //    , new SearchFilter.SearchFilterCollection(
                    //        LogicalOperator.Or,
                    //        new SearchFilter.ContainsSubstring(ItemSchema.Subject, subject),
                    //        new SearchFilter.ContainsSubstring(ItemSchema.Subject, subject2))
                    //    , view);

                    findResults = service.FindItems(
                        f2.Id
                        , new SearchFilter.IsEqualTo(EmailMessageSchema.Subject, subject2)
                        , view);

                    service.LoadPropertiesForItems(findResults, PropertySet.FirstClassProperties);

                    foreach (Item item in findResults)
                    {
                        // Get all properties of email message
                        PropertySet pset = new PropertySet(BasePropertySet.FirstClassProperties);
                        // Get the body in text
                        pset.RequestedBodyType = Microsoft.Exchange.WebServices.Data.BodyType.Text;
                        // Do an Item.Bind() to retrieve the Item
                        EmailMessage msg = Item.Bind(service, item.Id, pset) as EmailMessage;

                        // Refresh
                         //msg.Load();

                         if (!String.IsNullOrEmpty(msg.Body.Text))
                         {

                         }
                    }
                } while (findResults.MoreAvailable);


                //FindItemsResults<Item> findResults = service.FindItems(WellKnownFolderName.Inbox, new ItemView(10));
                //FindItemsResults<Item> findResults = service.FindItems(folder.Id, "from:admin@korablik.ru", new ItemView(folder.TotalCount));
                //FindItemsResults<Item> findResults = service.FindItems(folder.Id, new ItemView(10));

                /*
                PropertySet itemProp = new PropertySet(
                     ItemSchema.Id
                    , ItemSchema.Size
                    , ItemSchema.ItemClass
                    , ItemSchema.Subject
                    , ItemSchema.DateTimeReceived
                    , ItemSchema.DateTimeCreated
                    , ItemSchema.Categories
                    , ItemSchema.DisplayCc
                    , ItemSchema.DisplayTo);

                ItemView view = new ItemView(10);
                view.OrderBy.Add(ItemSchema.DateTimeReceived, SortDirection.Ascending);
                view.PropertySet = itemProp;

                FindItemsResults<Item> findResults = 
                    service.FindItems(
                    f2.Id
                    , new SearchFilter.IsEqualTo(EmailMessageSchema.Subject, subject)
                    , view);

                //service.LoadPropertiesForItems(findResults, new PropertySet(ItemSchema.Body));
                service.LoadPropertiesForItems(findResults, itemProp);
                
                foreach (Item item in findResults.Items)
                {                    
                    // Get all properties of email message
                    PropertySet pset = new PropertySet(BasePropertySet.FirstClassProperties);
                    // Get the body in text
                    pset.RequestedBodyType = Microsoft.Exchange.WebServices.Data.BodyType.Text;
                    // Do an Item.Bind() to retrieve the Item
                    EmailMessage msg = Item.Bind(service, item.Id, pset) as EmailMessage;
                    msg.Load();
                }
                */



            }
            catch (Exception err)
            {
                MessageBox.Show(err.Message);
            }

        }

        Folder ListFoldersInInbox(ref ExchangeService service, ref Folder f)
        {
            Folder ret = null;
            FindFoldersResults findResults = service.FindFolders(f.Id, new FolderView(10));

            foreach (Folder folder in findResults.Folders)
            {
                if (folder.DisplayName == "Опрос с сайта")
                {
                    ret = folder;
                    return ret;
                }                
            }
            /*
            FolderView FView = new FolderView(10);
            FindFoldersResults res =
                service.FindFolders(WellKnownFolderName.Inbox, FView);
            foreach (Folder fol in res)
            {
            }
            */
            return ret;
        }
    }
}
